package ar.com.tallerdos.smartdinner.adapter;

import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import ar.com.tallerdos.smartdinner.R;
import ar.com.tallerdos.smartdinner.model.Identity;

    
public class SeleccionMultipleAdapter<T extends Comparable<T> & Identity> extends BaseAdapter implements OnClickListener {
    private List<T> coleccion;
    private Boolean[] itemsSeleccionados;
    private Activity context;
    
    public SeleccionMultipleAdapter(Activity context, List<T> coleccion, List<T> seleccion) {
	this.coleccion = coleccion;
	for (T t : seleccion) {
	    if (!this.coleccion.contains(t)) {
		this.coleccion.add(t);		
	    }
	}
	Collections.sort(this.coleccion);
	this.context = context;
	this.itemsSeleccionados = new Boolean[coleccion.size()];
	for (int i = 0; i < coleccion.size(); i++) {
	    if (seleccion.contains(coleccion.toArray()[i])) {
		this.itemsSeleccionados[i] = Boolean.valueOf(true);
	    } else {
		this.itemsSeleccionados[i] = Boolean.valueOf(false);
	    }	    
	}
    }

    @Override
    public int getCount() {
	return this.coleccion.size();
    }

    @Override
    public Object getItem(int position) {
	return this.coleccion.get(position);
    }

    @Override
    public long getItemId(int position) {
	return this.coleccion.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.seleccion_multiple_row, null);
        }       
        
        CheckBox cb = (CheckBox) convertView.findViewById(R.id.seleccionMultipleChkBox);
        cb.setChecked(this.itemsSeleccionados[position]);
        cb.setTag(Integer.valueOf(position));
        cb.setOnClickListener(this);
        
        TextView descripcion = (TextView) convertView.findViewById(R.id.seleccionMultipleLabel);
        descripcion.setText(this.coleccion.get(position).toString());
        
        return convertView;
    }

    @Override
    public void onClick(View view) {
	Integer position = (Integer) view.getTag();
	this.itemsSeleccionados[position] = (((CheckBox) view).isChecked());	
    }

    public Boolean[] getItemsSeleccionados() {
        return itemsSeleccionados;
    }

    public void setItemsSeleccionados(Boolean[] mesasSeleccionadas) {
        this.itemsSeleccionados = mesasSeleccionadas;
    }
    
}
